package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.object.business.PageData;
import com.tbit.uqbike.object.pojo.AccountUser;
import com.tbit.uqbike.object.pojo.dto.AccountUserDTO;
import com.tbit.uqbike.object.pojo.dto.UpdatePasswordDTO;
import com.tbit.uqbike.object.pojo.vo.AccountUserLoginExportVO;
import com.tbit.uqbike.object.pojo.vo.BatchOperationMsgVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.base.RedisService;
import com.tbit.uqbike.service.business.AccountService;
import com.tbit.uqbike.service.business.AccountUserService;
import com.tbit.uqbike.service.rpcservice.SmsService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import com.tbit.utils.DateTimeUtil;
import com.tbit.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2020-01-03 16:26
 */
@Validated
@RestController
@RequestMapping(value = "/accountUser", produces = BaseController.MEDIA_JSON_UTF8)
public class AccountUserController extends BaseController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private RedisService redisService;

    @RequestMapping("/getAccountUserInfo")
    public JsonResult getAccountUserInfo(HttpServletRequest request) {
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        AccountUser accountUser = accountService.getAccountUserInfoById(loginInfo);
        // 处理敏感信息
        if (null != accountUser) {
            accountUser.setRoleName(loginInfo.getRoles() == null ? "" : loginInfo.getRoles().get(0) == null ? "" : loginInfo.getRoles().get(0).getRoleName());
            accountUser.setHasPassword(StrUtil.isBlank(accountUser.getPassword()) ? 0 : 1);
            accountUser.setPassword(null);
        }
        return JsonResult.ok(accountUser);
    }

    // 获取绑定的账号列表
    @RequestMapping("/getAccountUserList")
    public JsonResult getAccountUserList(HttpServletRequest request, @NotNull(message = "ver.accountId.notNull") Integer accountId, Integer rowCount, Integer pageNO, String phone, String name) {
        if (null == rowCount && null == pageNO) {
            // 全部获取
        } else {
            // 分页获取
            if (null == rowCount || rowCount <= 0 || rowCount > 1000) {
                rowCount = 20;
            }
            if (null == pageNO || pageNO < 1) {
                pageNO = 1;
            }
        }
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
//        PageData<List<AccountUser>> data = accountUserService.getAccountUserList(loginInfo, accountId, rowCount, pageNO);
        PageData<List<AccountUserDTO>> data = accountUserService.getAccountUserLists(loginInfo, accountId, rowCount, pageNO, phone, name);
        return JsonResult.ok(data.getData(), data.getTotal());
    }

    /**
     * 获取账号绑定列表
     *
     * @param brandId     品牌id
     * @param subRoleType 角色id
     * @param name        姓名
     * @param phone       手机号
     * @param accountId   筛选区域的id
     * @param pageNo      页码
     * @param pageSize    每页数量
     */
    @GetMapping("/getAccountUserListNew")
    public JsonResult getAccountUserListNew(@NotNull Integer brandId, @NotNull Integer subRoleType, String name, String phone,
                                            Integer accountId, @NotNull Integer pageNo, @NotNull Integer pageSize) {

        LoginInfo loginInfo = getLogin(ServletUtils.getRequest());
        PageInfo<AccountUserDTO> pageInfo = accountUserService.getAccountUserList(loginInfo, brandId, subRoleType,
                phone, name, accountId, pageNo, pageSize);
        return JsonResult.ok(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 根据角色id判断当前账号是否有权限查看角色绑定的账号
     *
     * @param roleId 品牌id
     */
    @GetMapping("/checkViewRoleAccountPermission")
    public Result<Boolean> checkViewRoleAccountPermission(@NotNull Integer roleId) {

        LoginInfo loginInfo = getLogin(ServletUtils.getRequest());

        return Result.success(accountUserService.checkViewRoleAccountPermission(roleId, loginInfo));
    }

    /**
     * @param request
     * @param accountId
     * @param subRoleType 子级角色类型:0 表示跟主权限一致，0是默认值
     *                    1:表示区域运维管理员
     *                    2:表示区域运维人员
     *                    6:表示区域客服
     *                    7:代表股东
     * @param expireDate
     * @param accountUser
     * @return com.tbit.uqbike.object.view.JsonResult
     * @Description:
     * @createDate 2020/9/28 18:41
     */
    // 绑定账号
    @RequestMapping("/addAccountUser")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ACCOUNTUSER_ADD)
    public JsonResult addAccountUser(HttpServletRequest request, @NotNull(message = "ver.accountId.notNull") Integer accountId,
                                     @NotNull(message = "ver.subRoleType.notNull") Integer subRoleType, Long expireDate, AccountUser accountUser, @RequestParam(value = "regionIds", required = false) String regionIds) {
        Assert.notNull(accountUser.getPhone(), "ver.phone.notNull");
        Assert.notNull(accountUser.getName(), "ver.name.notNull");
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);

        if (null == accountUser.getCountry() || accountUser.getCountry().isEmpty()) {
            accountUser.setCountry("86");
        }
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        /***/
        String date = null;
        if (expireDate != null) {
            date = DateTimeUtil.format(new Date(expireDate), DateUtil.YMD_);
        }
        //添加客服角色时，前端未传profitLimit时为null，null插入异常，所以默认为0
        if (null == accountUser.getProfitLimit()) {
            accountUser.setProfitLimit(0);
        }
        accountUserService.addAccountUser(loginInfo, accountId, subRoleType, accountUser, date, regionIdList);
        return JsonResult.ok();
    }

    // 删除账号
    @RequestMapping("/delAccountUser")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ACCOUNTUSER_DEL)
    public JsonResult delAccountUser(HttpServletRequest request, @NotNull(message = "ver.accountId.notNull") Integer accountId,
                                     @NotNull(message = "ver.accountUserId.notNull") Integer accountUserId) {
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        accountUserService.delAccountUser(loginInfo, accountId, accountUserId);
        return JsonResult.ok();
    }

    @GetMapping("/export/loginAccount")
    public Result<String> exportLoginAccount(HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        ExcelUtil<AccountUserLoginExportVO> excelUtil = new ExcelUtil<>(AccountUserLoginExportVO.class);
        List<AccountUserLoginExportVO> list = accountUserService.queryAccountUserByAccountId(loginInfo.id, loginInfo.getType());
        return Result.success(excelUtil.exportExcel(list, "平台账号列表").getData().toString());
    }

    // 修改账号信息
    @RequestMapping("/modAccountUser")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ACCOUNTUSER_EDIT)
    public JsonResult modAccountUser(HttpServletRequest request, AccountUser accountUser, Long expireTime, String regionIds) {
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        if (accountUser.getEmail() == null) {
            accountUser.setEmail("");
        }
        if (accountUser.getRemark() == null) {
            accountUser.setRemark("");
        }
        if (expireTime != null) {
            accountUser.setExpireDate(DateTimeUtil.DateTimeToString(new Date(expireTime)));
        }
        accountUserService.modAccountUser(loginInfo, accountUser, regionIdList);
        return JsonResult.ok();
    }

    //获取区域所有运维人员
    @RequestMapping("/getByType")
    public JsonResult getByType(@NotNull(message = "ver.accountId.notNull") Integer accountId) {
        List<AccountUser> list = accountUserService.getByType(accountId, true);
        return JsonResult.ok(list);
    }

    /**
     * 查询是否手机号码位置
     *
     * @param phone
     * @return
     */
    @RequestMapping("/getByPhone")
    public JsonResult getAccountIdByPhone(String phone, String name, HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        Integer brandId = loginInfo.roleNotAdmin() ? loginInfo.getBrandId() : null;
        String msg = accountUserService.getAccountIdByPhone(brandId, phone, name);
        return JsonResult.ok(msg);
    }

    /**
     * 通过类型查询
     *
     * @param accountId   区域id
     * @param subRoleType 类型
     * @return
     */
    @RequestMapping("/getByUserType")
    public JsonResult getByUserType(@NotNull(message = "ver.accountId.notNull") Integer accountId, @NotNull(message = "ver.subRoleType.notNull") Integer subRoleType) {
        List<AccountUser> list = accountUserService.getByUserType(accountId, subRoleType);
        return JsonResult.ok(list);
    }

    /* 查询发送验证码*/
    @RequestMapping("/getAuthCode")
    public JsonResult getAuthCode(@NotNull(message = "ver.accountUserId.notNull") Integer accountUserId) {
        AccountUser user = accountUserService.getAccountUserById(accountUserId);
        return JsonResult.ok(redisService.get(SmsService.getCodeRedisKey(user.getCountry(), user.getPhone(), SmsService.CODE_LOGIN)));
    }

    /**
     * 更新用户密码
     *
     * @param dto
     * @return
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordDTO dto, String token) {
        Assert.notNulls("参数有误", dto.getAccountUserId(), dto.getPassword(), token);
        accountUserService.updatePassword(token, dto.getAccountUserId(), dto.getPassword());
        return Result.success();
    }

    /**
     * 批量修改账号角色
     *
     * @param phoneList   手机号
     * @param subRoleType 0:默认值 1:区域运维管理员 2:区域运维人员 6:区域客服 7:股东
     * @param accountId   品牌、加盟商、区域
     * @param roleLevel   1:品牌 2:加盟商 3:区域
     * @return result
     */
    @PostMapping("/batchUpdateUserRole")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ROLE_UPDATE)
    public Result<BatchOperationMsgVO<String>> batchUpdateUserRole(String phoneList, Integer subRoleType, Integer brandId, Integer accountId, Integer roleLevel) {
        Assert.notNulls("参数有误", phoneList, subRoleType, accountId, roleLevel);
        return accountUserService.batchUpdateUserRole(phoneList, subRoleType, brandId, accountId, roleLevel);
    }

    /**
     * 获取所有父级账号
     *
     * @param accountId 区域id
     * @return List
     */
    @PostMapping("/getParentsAccountUser")
    public Result<Object> getParentsAccountUser(Integer accountId, HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        return accountUserService.getParentsAccountUser(accountId, loginInfo);
    }

    /**
     * @description: 根据品牌id获取当前用户能看到的所有用户（管理员和品牌能看到该品牌下的所有用户，加盟商能看到加盟商级别和区域级别的用户，区域用户只能看到区域级别的用户）
     * @author: mo.shanyong
     * @date: 2025/2/26 15:49
     * @param: brandId 品牌id
     * @param: request
     * @return: Result<java.lang.Object>
     */
    @GetMapping("/getAUserByBrandAndUser")
    public Result<Object> getAUserByBrandAndUser(Integer brandId, HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        List<AccountUser> accountUserList = accountUserService.getAUserByBrandAndUser(brandId, loginInfo);
        return Result.success(accountUserList);
    }
}
